package com.ujs.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ujs.commonutils.constant.R;
import com.ujs.commonutils.utils.JwtUtils;
import com.ujs.eduservice.entity.EduCourse;
import com.ujs.eduservice.entity.course.ChapterVo;
import com.ujs.eduservice.entity.vo.frontVo.CourseFrontVo;
import com.ujs.eduservice.entity.vo.frontVo.CourseWebVo;
import com.ujs.eduservice.feign.OrderFeignService;
import com.ujs.eduservice.service.EduChapterService;
import com.ujs.eduservice.service.EduCourseService;
import com.ujs.servicebase.entity.CourseVoOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author zhangshihao
 * @create 2023-09-01 21:34
 */
@RequestMapping("/eduservice/front/course")
@RestController
@Api(tags = "前台课程管理")
public class CourseFrontController {
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private OrderFeignService orderFeignService;

    @PostMapping("/getFrontCourseList/{page}/{limit}")
    @ApiOperation("根据查询条件，获取课程列表")
    public R getFrontCourseList(@RequestBody(required = false) CourseFrontVo courseFrontVo, @PathVariable long page, @PathVariable long limit) {
        Page<EduCourse> eduCoursePage = new Page<>(page, limit);
        Map<String, Object> map = courseService.getFrontCourseList(courseFrontVo, eduCoursePage);
        return R.ok().data(map);
    }

    @GetMapping("/getFrontCourseInfo/{courseId}")
    @ApiOperation("根据课程ID查询课程信息")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {
        // 查询课程数据
        CourseWebVo courseWebVo = courseService.getCourseBaseInfo(courseId);
        // 查询章节和小节
        List<ChapterVo> chapterVideo = chapterService.getChapterVideo(courseId);
        if (!StringUtils.isEmpty(JwtUtils.getMemberIdByJwtToken(request))) {
            // 根据课程id和用户id查询当前课程是否已经被购买过了
            Boolean isBuy = orderFeignService.getOrderStatus(courseId, JwtUtils.getMemberIdByJwtToken(request));
            return R.ok().data("courseWebVo", courseWebVo).data("chapterVideo", chapterVideo).data("isBuy", isBuy);
        }
        return R.ok().data("courseWebVo", courseWebVo).data("chapterVideo", chapterVideo);
    }

    @ApiOperation("负责订单的远程调用，根据课程id返回信息")
    @GetMapping("/getCourseInfoById/{courseId}")
    public CourseVoOrder getCourseInfoById(@PathVariable("courseId") String courseId) {
        return courseService.getCourseInfoById(courseId);
    }
}
